#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : lei.wang
import hashlib
import uuid
from typing import Annotated
from fastapi import APIRouter, Depends
from app.core.db.database import async_get_db
from app.schemes.login import LoginModel, RefreshTokenModel
from app.schemes.score import UserScoreCreate
from app.schemes.user import UserCreate
from app.services.user import UserService, UserScoreService
from sqlalchemy.ext.asyncio import AsyncSession
from app.util.jwt_helper import generate_jwt_token, refresh_jwt_token
from app.util.password_validator import validate_password
from app.core.config import config

login_router = APIRouter(tags=["登录&&注册"])


@login_router.post("/register", description="注册")
async def register(model: LoginModel, db: Annotated[AsyncSession, Depends(async_get_db)]): 
    user_service = UserService(db)
    if await user_service.check_user_exist(model.username):
        return {"success": False, "message": "用户已存在", "data": {}}
    
    if not validate_password(model.password):
        return {"success": False, "message": "密码长度至少8位, 包含大小写字母和数字", "data": {}}
    
    # 密码加密
    password = hashlib.md5(model.password.encode()).hexdigest()
    user_obj = UserCreate(username=model.username, password=password, payload_id=uuid.uuid4().hex)
    user = await user_service.create_user(user_obj)

    # 用户创建增加对应积分
    user_score_service = UserScoreService(db)
    user_score_obj = UserScoreCreate(
        payload_id=user.payload_id, 
        total_score=config.get("score").get("register"), 
        used_score=0
    )
    await user_score_service.create_user_score(user_score_obj)
    return {"success": True, "message": "success", 'data': user}


@login_router.post("/login", description="登录")
async def login(model: LoginModel, db: Annotated[AsyncSession, Depends(async_get_db)]):
    user_service = UserService(db)
    if not await user_service.check_user_exist(model.username):
        return {"success": False, "message": "用户不存在", "data": {}}
    # 密码校验
    password = hashlib.md5(model.password.encode()).hexdigest()
    user = await user_service.get_user_by_username(model.username)
    if user.get("password") != password:
        return {"success": False, "message": "密码错误", "data": {}}
    
    # 生成token
    token = generate_jwt_token(user.get("payload_id"))
    return {"success": True, "message": "登录成功", "data": {"token": token, 'username': user.get("username", "")}}


@login_router.post("/refresh_token", description="刷新token")
async def refresh_token(model: RefreshTokenModel):
    """刷新token接口
    当token过期时，客户端可以使用此接口刷新token，无需重新登录
    """
    try:
        # 刷新token
        new_token = refresh_jwt_token(model.expired_token)
        return {"success": True, "message": "token刷新成功", "data": {"token": new_token}}
    except Exception as e:
        return {"success": False, "message": f"token刷新失败: {str(e)}", "data": {}}
